#include "SensorCom.h"

char gl_Registered;

int gl_TimeToSleep;

unsigned char gl_NodeID[4] = "c00";

void sendInfoToCoordinator(unsigned char *info, int dataLen)
{
    FrameAPI myApiFrame;

    unsigned char adresseDEST_H[4] = {0x00, 0x00, 0x00, 0x00};
    unsigned char adresseDEST_L[4] = {0x00, 0x00, 0x00, 0x00};
    unsigned char adresseDEST_16Bits[2] = {0xFF, 0xFE};

    makeDataTransmitFrame(&myApiFrame, info, dataLen, adresseDEST_H, adresseDEST_L, adresseDEST_16Bits);

    displayAPIFrame(myApiFrame);

    sendAPI(myApiFrame);

    waitForTransmitStatusPacket();
}

void handleDataPacket(FrameAPI fApi)
{
    switch(fApi.content.frame.api.receivePacket.rcvData[0])
    {
        case COORD_REGISTER_RESPONSE :
            if(fApi.content.frame.api.receivePacket.rcvData[1] == REGISTER_SUCCESS)
            {
                if(gl_Registered == 0)
                {
                    printf("<?>DEBUG - Device Registred\n");
                    gl_Registered = 1;
                }
                else
                {
                    printf("<?>DEBUG - Register response received but device already registered\n");
                }
            }
            else
            {
                int nodeIDSize = fApi.length_LSB - HS_RCV_PACKET - 1;
                int iCpt = 0;
                for(iCpt = 0 ; iCpt < nodeIDSize ; iCpt ++)
                {
                    gl_NodeID[iCpt] = fApi.content.frame.api.receivePacket.rcvData[iCpt + 2];
                }
                gl_NodeID[iCpt] = 0;
                printf("<?>DEBUG - Device Registred with a new NodeID : %s\n", gl_NodeID);
                setNodeId(gl_NodeID);
            }
            break;

        case COORD_DATA_REQUEST :
            printf("<?>DEBUG - Retransmit data packet\n");
            sendSensorData();
            break;

        case COORD_SLEEP_REQUEST :
            setTimeToSleep(fApi.content.frame.api.receivePacket.rcvData[1]*256 + fApi.content.frame.api.receivePacket.rcvData[2]%256);
            printf("<?>DEBUG - Sleep Mode Requested for %d seconds\n",getTimeToSleep());
            break;

        default:
            printf("<!>ERROR - Unhandled packet\n");
            break;
    }
}

void setNodeId(unsigned char *nodeId)
{
    FrameAPI myApiFrame;

    unsigned char ATNI[3] = "NI";

    makeATFrame(&myApiFrame, ATNI, nodeId, 0x52);

    sendAPI(myApiFrame);
}

void getNodeId()
{
    unsigned char void_parameter[1];

    unsigned char ATNI[3] = "NI";

    void_parameter[0] = '\0';

    FrameAPI myApiFrame;

    makeATFrame(&myApiFrame, ATNI, void_parameter, 0x52);

    sendAPI(myApiFrame);
}

void initSensor()
{
    gl_Registered = 0;

    gl_TimeToSleep = 0;

    setNodeId(gl_NodeID);

    initClock();

    #ifdef SENSOR_PC
    #define PORT_COM_STR "COM3"
    initPortSerie(PORT_COM_STR);
    #endif
}

char registerDevice()
{
    if(gl_Registered == 0)
    {
        FrameAPI myApiFrame;
        int registerRetransmit = 0;
        //printf("<?>DEBUG - First try to register\n");
        sendRequestRegister();
        while(recept(&myApiFrame, 3) == 0)
        {
            //printf("<?>DEBUG - No response...\n");
            registerRetransmit++;
            if(registerRetransmit < 5)
            {
                //printf("<?>DEBUG - Retry count %d\n",registerRetransmit);
                sendRequestRegister();
            }
            else
            {
                //printf("<!>ERROR - Sensor \"%s\" not registered after 5 retransmit !\n", gl_NodeID);
                return 0;
            }
            //printf("<?>DEBUG - Wait for response...\n");
        }
        if(myApiFrame.content.frame.frameType == API_CMD_RECV_PACKET)
        {
            //printf("<?>DEBUG - Packet Received\n");
            handleDataPacket(myApiFrame);
        }
    }
    return 1;
}

void sendRequestRegister()
{
    int iCpt = 1;
    unsigned char data[32];
    // Frame type : Request Register
    data[0] = SENSOR_REGISTER_REQUEST;

    // Adding the Node ID from the soft parameters
    while(gl_NodeID[iCpt - 1] != '\0')
    {
        data[iCpt] = gl_NodeID[iCpt - 1];
        iCpt++;
    }
    data[iCpt] = '\0';
    sendInfoToCoordinator(data, iCpt);
}


// Sensor Data Frame : <FrameType><NodeID>'*'<Data>
void sendSensorData()
{
    int iCpt = 1;
    unsigned char data[32];
    data[0] = SENSOR_DATA_PACKET;
    while(gl_NodeID[iCpt - 1] != '\0')
    {
        data[iCpt] = gl_NodeID[iCpt - 1];
        iCpt++;
    }
    data[iCpt] = '*';
    iCpt ++;
    iCpt += getSample(data + iCpt);
    data[iCpt] = '\0';
    sendInfoToCoordinator(data, iCpt);
}

int getTimeToSleep()
{
    return gl_TimeToSleep;
}

void setTimeToSleep(int tts)
{
    gl_TimeToSleep = tts;
}

int getSample(unsigned char *buff)
{
    buff[0] = '1';
    buff[1] = '2';
    buff[2] = '3';
    buff[3] = '4';
    buff[4] = '5';
    buff[5] = '6';
    return 6;
}

